package com.netflexitysolutions.amazonws.s3.internal.operations;

import java.util.ArrayList;
import java.util.List;

import com.amazonaws.s3.doc._2006_03_01.CanonicalUser;
import com.amazonaws.s3.doc._2006_03_01.ListBucket;
import com.amazonaws.s3.doc._2006_03_01.ListBucketResult;
import com.amazonaws.s3.doc._2006_03_01.ListEntry;
import com.netflexitysolutions.amazonws.s3.S3;
import com.netflexitysolutions.amazonws.s3.S3Bucket;
import com.netflexitysolutions.amazonws.s3.S3Object;
import com.netflexitysolutions.amazonws.s3.S3Owner;

public class ListBucketOperation extends OperationExecutor<ListBucket, S3Bucket>{

    private String prefix;
    private String marker;
    private String delimiter;
    private int maxKeys;
    private String bucket;


	/**
	 * @param s3
	 */

	public ListBucketOperation(S3 s3, String bucket, String prefix, String marker, String delimiter, int maxKeys) {
		super(s3);
        this.bucket = bucket;
        this.prefix = prefix;
        this.marker = marker;
        this.delimiter = delimiter;
        this.maxKeys = maxKeys;
	}

	/* (non-Javadoc)
	 * @see com.netflexitysolutions.amazonws.s3.internal.operations.OperationExecutor#call(java.lang.Object)
	 */
	@Override
	protected S3Bucket call(ListBucket request) {

        request.setBucket(bucket);
        if(prefix != null){
            request.setPrefix(prefix);
        }
        if(marker != null){
            request.setMarker(marker);
        }
        if(delimiter != null){
            request.setDelimiter(delimiter);
        }
        if(maxKeys > 0){
            request.setMaxKeys(maxKeys);
        }

        injectCredentials(request, "ListBucket", getS3().getAccessKey(), getS3().getSecretKey());
        ListBucketResult response = getS3().getService().listBucket(request).getListBucketResponse();

        List<ListEntry> entries = response.getContents();
        List<S3Object> list = new ArrayList<S3Object>(entries.size());
        for(ListEntry entry : entries){
            S3Object obj = new S3Object(entry.getKey());
            obj.setETag(entry.getETag());
            obj.setLastModifiedDate(entry.getLastModified());
            obj.setStorageClass(entry.getStorageClass().name());
            CanonicalUser owner = entry.getOwner();
            obj.setOwner(new S3Owner(owner.getID(), owner.getDisplayName()));
            list.add(obj);
        }
        S3Bucket rv = new S3Bucket();
        rv.setName(response.getName());
        rv.setNextMarker(response.getNextMarker());
        rv.setTruncated(response.isIsTruncated());
        rv.setContent(list);
        return rv;
	}
}
